package nettyteach.reconnheart;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author ligengxian
 * @Date 2022/4/24 上午10:56
 * @Version 1.0
 * @Description:通过ChannelFutureLister接口实现客户端自动重连，区别于断线重连
 **/
public class ListenerClientReconnHeart implements ChannelFutureListener {
    private AppClientReconnHeart appClientReconnHeart=new AppClientReconnHeart("127.0.0.1",18080);
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {

        //首先判断状态是否正常,不正常每5秒进行重连操作
        if (!channelFuture.isSuccess()){
            EventLoop loop=channelFuture.channel().eventLoop();
            ScheduledFuture<?>scheduled=loop.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("自动启动客户端，开始连接服务器");
                        appClientReconnHeart.run();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            },5, TimeUnit.SECONDS);
        }else {
            System.out.println("服务器连接成功");
        }
    }
}


